package gr.handmademarket.ui.forms;

import gr.handmademarket.bl.operations.ChangePasswordOperation;
import gr.handmademarket.po.enums.Role;
import gr.handmademarket.po.interfaces.User;
import gr.handmademarket.ui.pages.HomePage;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

public class ChangePasswordForm 
extends Form<User>{

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	private String username;
	private Role role;
	
	private PasswordTextField oldPasswordField = new PasswordTextField("oldPassword", Model.of(""));
	private PasswordTextField newPasswordField = new PasswordTextField("newPassword", Model.of(""));
	private PasswordTextField retypePasswordField = new PasswordTextField("retypePassword", Model.of(""));
	private FeedbackPanel feedback = new FeedbackPanel("feedback");
	private AjaxButton submit = new AjaxButton("passwordBtn") {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		@Override
		protected void onSubmit(AjaxRequestTarget target, Form<?> form1) {
			ChangePasswordOperation op = new ChangePasswordOperation();
			op.setOldPassword(oldPasswordField.getModelObject());
			op.setNewPassword(newPasswordField.getModelObject());
			op.setRetypePassword(retypePasswordField.getModelObject());
			op.setRole(role);
			op.setUsername(username);
			try{
				op.execute();
				feedback.getFeedbackMessages().clear();
				HomePage homePage = new HomePage();
				setResponsePage(homePage);
			}catch (RuntimeException e){
				error(e.getMessage());
				target.add(feedback);
			}
		}
	};
	
	public ChangePasswordForm(String id, IModel<User> model) {
		super(id, model);
		username = model.getObject().getUsername();
		role = model.getObject().getRole();
		oldPasswordField.setRequired(true);
		newPasswordField.setRequired(true);
		retypePasswordField.setRequired(true);
		add(oldPasswordField,newPasswordField,retypePasswordField,submit,feedback);
		setOutputMarkupId(true);
		feedback.setOutputMarkupPlaceholderTag(true);
	}

}
